import jsapi from './../config/jsapi.json';
import DB from './../app/db';
import nattyStorage from 'natty-storage';
import {Popup} from 'saltui';

const {jsonConfig} = require('./../contas/contas.js');

const storageUser = nattyStorage({
  type: 'localStorage',  // 缓存方式, 默认为'localStorage'
  key: 'sskj-dingtalk-user',     // !!! 唯一必选的参数, 用于内部存储 !!!
  tag: 'v1.0.0.1',          // 缓存的标记, 用于判断是否有效
  duration: 1000 * 60 * 100,      // 缓存的有效期长, 以毫秒数指定
});

class DingClient {


  ddConfig() {

    let jsapiArr = [];
    for (var i in jsapi) {
      jsapi[i]
        ? jsapiArr.push(i)
        : ""
    }
    DB.config.get(jsonConfig).then(
      function (content) {
        let data = content;

        dd.config({
          agentId: data.agentId,
          corpId: data.corpId,
          timeStamp: data.timeStamp,
          nonceStr: data.nonceStr,
          signature: data.signature,
          jsApiList: jsapiArr
        });
        dd.error(function (error) {
          alert(JSON.stringify(error))
        });

        dd.ready(function () {

          dd.runtime.permission.requestAuthCode({
            corpId: data.corpId,
            onSuccess: function (result) {
              DB.user.get({
                code: result.code,
                corpId: data.corpId
              }).then(
                function (content) {
                  storageUser.data(content);
                },
                function (error) {
                  alerr('钉钉身份验证接口失败!' + JSON.stringify(error));
                });
            },
            onFail: function (err) {
              alert("钉钉免登服务错误!" + JSON.stringify(err));
            }
          });
        });
      }, function (error) {
        alert('钉钉身份验证接口失败!' + JSON.stringify(error));
      });
  };


}

export default new DingClient();
